#!/bin/bash

# ============================================
# 修复 Nginx 配置（恢复备份并正确注释）
# ============================================

echo "=== 恢复备份 ==="
sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf

echo ""
echo "=== 查看默认 server 块的行号 ==="
grep -n "listen.*80 default_server" /etc/nginx/nginx.conf
grep -n "^    }" /etc/nginx/nginx.conf | head -5

echo ""
echo "=== 正确注释掉默认 server 块 ==="
# 找到 server 块的开始和结束
# 使用更精确的方法：找到包含 default_server 的 server 块并注释掉
sudo sed -i '/server {/,/^    }/{
    /listen.*80 default_server/,/^    }/{
        s/^/# /g
    }
}' /etc/nginx/nginx.conf

# 或者更简单：直接删除 default_server 关键字，让其他 server 块成为默认
sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf
sudo sed -i 's/listen.*80 default_server;/listen       80;/' /etc/nginx/nginx.conf
sudo sed -i 's/listen.*\[::\]:80 default_server;/listen       [::]:80;/' /etc/nginx/nginx.conf

echo ""
echo "=== 验证配置 ==="
sudo nginx -t

echo ""
echo "=== 重启 Nginx ==="
sudo systemctl restart nginx

echo ""
echo "=== 测试 ==="
sleep 1
curl -v http://127.0.0.1/api/login/ 2>&1 | head -20

echo ""
echo "✓ 修复完成！"

